﻿using SSHTool.Model;
using System.Collections.Generic;
using System.Linq;

namespace SSHTool.Service
{
    public class CmdLogService : JsonFileService
    {
        private readonly string file_name = "cmd_log_{0}.json";

        private int connectionId = 0;

        public override string FileName => string.Format(file_name, connectionId);

        public CmdLogService UpdateConnectionId(int connectionId)
        {
            this.connectionId = connectionId;

            return this;
        }

        public List<CmdLogModel> GetList(int connectionId)
        {
            this.UpdateConnectionId(connectionId);

            var list = GetList<CmdLogModel>();

            if (list == null)
            {
                list = new List<CmdLogModel>();
            }

            return list.OrderBy(m => m.Id).ToList();
        }

        public void AddCmd(string cmd, List<CmdLogModel> list, bool allowRepeat = true)
        {
            if (string.IsNullOrEmpty(cmd))
            {
                return;
            }

            if (list == null)
            {
                list = new List<CmdLogModel>();
            }

            if (!allowRepeat)
            {
                var model = list.FirstOrDefault(m => m.Cmd == cmd);

                if (model != null)
                {
                    return;
                }
            }

            int maxId = 0;

            if (list.Count > 0)
            {
                maxId = list.Max(m => m.Id);
            }

            maxId++;

            CmdLogModel cmdModel = new CmdLogModel(maxId, cmd);
            list.Add(cmdModel);

            Update(list);
        }

        public string GetCmd(int index, List<CmdLogModel> list)
        {
            try
            {
                var model = list[index];

                if (model != null)
                {
                    return model.Cmd;
                }
                return "";
            }
            catch
            {
                return "";
            }
        }
    }
}
